#!/usr/bin/env bash

echo "Foreach run script"

# If memory smaller than 2GB, create swap to avoid OOM, please see
# https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-18-04
#
# Note that another solution is to disable GENERATE_SOURCEMAP to avoid OOM, but it doesn't work sometimes, please see
# https://create-react-app.dev/docs/advanced-configuration/
#
# Disable swap by: swapoff /srs-swapfile
MEM_TOTAL=$(grep MemTotal /proc/meminfo |awk '{print $2}')
if [[ MEM_TOTAL -lt 2097152 ]]; then
  if [[ ! -f /srs-swapfile ]]; then
    fallocate -l 2G /srs-swapfile && chmod 600 /srs-swapfile && ls -lh /srs-swapfile && mkswap /srs-swapfile &&
    echo "Create swap file ok"
    if [[ $? -ne 0 ]]; then echo "Create swap file failed"; exit 1; fi
  fi

  swapon --show |grep "/srs-swapfile"
  if [[ $? -ne 0 ]]; then
    swapon /srs-swapfile &&
    echo "Turn on swap /srs-swapfile for MEM_TOTAL=$MEM_TOTAL"
    if [[ $? -ne 0 ]]; then echo "Turn on swap memory failed"; exit 1; fi
  fi
fi

# Generate coredump, see https://stackoverflow.com/a/47694315/17679565
if [[ -f /proc/sys/kernel/core_pattern && ! -d /cores ]]; then
  echo '/cores/core.%e.%p' | tee /proc/sys/kernel/core_pattern &&
  mkdir -p /cores && echo "Create dirs for coredump"
  if [[ $? -ne 0 ]]; then echo "Create dirs failed"; exit 1; fi
fi

# Revert the redis config, after migrate to docker.
# Also setup the redis password, so we must keep running this script.
bash auto/setup_redis
if [[ $? -ne 0 ]]; then echo "Setup redis failed"; exit 1; fi

# We setup the docker network.
bash auto/setup_network
if [[ $? -ne 0 ]]; then echo "Setup docker network failed"; exit 1; fi

# Create directories for data, allow user to link it.
mkdir -p containers/data/dvr containers/data/prometheus containers/data/record containers/data/vod


